import axios from "axios";
import ElMessage from "@/hooks/usemessage"

const AxisoInstance = axios.create({
  baseURL: '/api'
});
const aSuccessMsg = ['成功']
const fnMessage = (res) => {
  if (res && res.msg) {
    const mesFunc = aSuccessMsg.includes(res.msg) ? ElMessage.success : ElMessage.error
    mesFunc(res.msg)
  }
}

export const fnGet = (url, params) => {
  return AxisoInstance.get(`${url}`, {
    params
  }).then(res => {
    fnMessage(res.data)
    return res.data
  }, err => {
    // fnMessage("error", "服务器错误")
    if (err.response && err.response.data) {
      fnMessage(err.response.data)
    }
    else {
      fnMessage({ msg: `服务器请求错误:${err}，如有疑问请联系开发人员` })
    }
    return null
  })
}

export const fnPost = (url, data) => {
  return AxisoInstance.post(`${url}`, {
    ...data
  }).then(res => {
    fnMessage(res.data)
    return res.data
  }, err => {
    // fnMessage("error", "服务器错误")
    if (err.response && err.response.data) {
      fnMessage(err.response.data)
    }
    else {
      fnMessage({ msg: `服务器请求错误:${err}，如有疑问请联系开发人员` })
    }
    return null
  })
}

export const fnFilePost = (url, data) => {
  return AxisoInstance.post(`${url}`, data, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    fnMessage(res.data)
    return res.data
  }, err => {
    // fnMessage("error", "服务器错误")
    if (err.response && err.response.data) {
      fnMessage(err.response.data)
    }
    else {
      fnMessage({ msg: `服务器请求错误:${err}，如有疑问请联系开发人员` })
    }
    return null
  })
}
export default AxisoInstance